#include "Socket.hpp"
#include "Common.hpp"
#include "Protcol.hpp"
#include <iostream>
#include <string>
#include <memory>

using namespace SocketModule;

void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << " server_ip server_port" << std::endl;
}
void GetDataFromStdin(int *x, int *y, char *oper)
{
    std::cout << "Please Enter x: ";
    std::cin >> *x;
    std::cout << "Please Enter y: ";
    std::cin >> *y;
    std::cout << "Please Enter oper: ";
    std::cin >> *oper;
}


int main(int argc, char*argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }

    std::string server_ip = argv[1];
    uint server_port = std::stoi(argv[2]);

    std::shared_ptr<Socket> client = std::make_shared<TcpSocket>();
    client -> BuildTcpClientMethod();

    if(client -> Connect(server_ip, server_port) == 0)
    {
        // 失败
        std::cerr << "connect error" << std::endl;
        exit(CONNECT_ERR);
    }

    std::unique_ptr<Protocol> protcol = std::make_unique<Protocol>();
    std::string resp_buffer;

    while(true)
    {
        //服务器连接成功
        int x, y;
        char oper;
        GetDataFromStdin(&x, &y, &oper);

        //建立一个请求 -- 可以直接发送的字符串
        std::string req_str = protcol->BuildRequestString(x, y, oper);

        //发送请求
        client -> Send(req_str);

        //获取应答
        Response resp;
        bool res = protcol->GetResponse(client, resp_buffer, &resp);
        if(res == false)
        {
            break;
        }

        //显示结果
        resp.ShowResult();
    }
    client->Close();
}